<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Queue;

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');
        return $this->fetch();
    }

    /**
     * 列表导出示例
     * */
    public function exportListDemo()
    {
        $title = '文件名';
        $th = ['标题一', '标题二', '标题三'];
        $td = ['key1', 'key2', 'key3'];
        $data = [
            [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ], [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ]
        ];

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            echo "<pre>";
            print_r($input);
            exit;
        }
        $this->assign('title', '表单示例');
        return $this->fetch();
    }

    /**
     * 视频分片上传示例
     * */
    public function uploadVideo()
    {
        $this->assign('title', '视频分片上传示例');
        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');
        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');
        return $this->fetch();
    }

    /**
     * 文章分类列表
     * */
    public function articleTypeList()
    {
        $list = Db::name('article_type')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '文章分类列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章分类
     * */
    public function doArticleType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('article_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'name' => $name
            ];

            if ($id > 0) {
                $res = Db::name('article_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('article_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '新增文章分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('article_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '文章分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章分类
     * */
    public function delArticleType()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '分类ID缺失');

        $info = Db::name('article_type')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article_type')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 文章列表
     * */
    public function articleList()
    {
        $list = Db::name('article')->order('sort asc')->paginate()->each(function ($v) {
            $type_info = Db::name('article_type')->where(['id' => $v['type_id']])->find();
            $v['type_name'] = $type_info['name'];

            return $v;
        });

        $type_list = Db::name('article_type')->select();

        $this->assign('list', $list);
        $this->assign('type_list', $type_list);
        $this->assign('title', '文章列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章
     * */
    public function doArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $vice_title = $input['vice_title'];
            $img = $input['img'];
            $type_id = $input['type_id'];
            $user_id = $input['user_id'];
            $sort = $input['sort'];
            $content = $input['content'];

            if (empty($title)) adminReturn(2, '请输入标题');
            if (empty($vice_title)) adminReturn(2, '请输入副标题');
            if (empty($img)) adminReturn(2, '请上传封面图');
            if (empty($type_id)) adminReturn(2, '请选择分类');
            if (empty($user_id)) adminReturn(2, '请选择作者');
            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'title' => $title,
                'vice_title' => $vice_title,
                'img' => $img,
                'type_id' => $type_id,
                'user_id' => $user_id,
                'sort' => $sort,
                'content' => $content
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('articleList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('articleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('article')->where(['id' => $id])->find();
            }

            $type_list = Db::name('article_type')->select();

            $user_list = Db::name('user')->select();

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文章');
            $this->assign('info', $info);
            $this->assign('type_list', $type_list);
            $this->assign('user_list', $user_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章
     * */
    public function delArticle()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文章ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 学员列表
     * */
    public function studentList()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        $where['user_type'] = 2;

        if ($mobile) $where['mobile'] = ['like', '%' . $mobile . '%'];
        if (!empty($start_time) && empty($end_time)) {
            $where["create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('user')->where($where)->paginate()->each(function ($v) {
            $teacher_username = '';
            if ($up_user_id = $v['up_user_id']) $teacher_username = Db::name('user')->where(['id' => $up_user_id])->value('username');
            $v['teacher_username'] = $teacher_username;

            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '学员列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 学员
     * */
    public function doStudent()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $username = $input['username'];
            $avatar = $input['avatar'];
            $mobile = $input['mobile'];
            $up_user_id = $input['up_user_id'];
            $password = $input['password'];
            $re_password = $input['re_password'];

            if (empty($username)) adminReturn(2, '请输入昵称');
            if (empty($avatar)) adminReturn(2, '请上传头像');
            if (empty($mobile)) adminReturn(2, '请输入手机号');
            if (!preg_match("/^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/", $mobile)) adminReturn(2, '手机号有误，请重新输入');
            if (empty($up_user_id)) adminReturn(2, '请选择老师');
            if (empty($password)) adminReturn(2, '请输入密码');
            if (strlen($password) < 6) adminReturn(2, '密码长度至少6位');
            if ($password !== $re_password) adminReturn(2, '两次密码不一致，请重新输入');

            $where['mobile'] = $mobile;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('user')->where($where)->count();
            if ($count > 0) adminReturn(2, '该手机号已被使用');

            $time = time();
            $data = [
                'username' => $username,
                'avatar' => $avatar,
                'mobile' => $mobile,
                'up_user_id' => $up_user_id,
                'password' => thinkEncrypt($password),
                'user_type' => 2
            ];

            if ($id) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('user')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('studentList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('user')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('studentList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $input = Request()->param();

            $id = $input['id'];

            $info = Db::name('user')->where(['id' => $id])->find();
            $info['password'] = thinkDecrypt($info['password']);
            $this->assign('info', $info);

            $teacher_list = Db::name('user')->where(['user_type' => 1])->select();
            $this->assign('teacher_list', $teacher_list);

            $this->assign('title', ($id ? '编辑' : '新增') . '学员');
            return $this->fetch();
        }
    }

    /**
     * 做题明细
     * */
    public function studentTopicLog()
    {
        $input = Request()->param();

        $id = $input['id'];// 学生id
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (empty($id)) $this->error('学生ID缺失');

        $where['user_id'] = $id;

        if (!empty($start_time) && empty($end_time)) {
            $where["create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('topic_log')->where($where)->order('create_time desc')->paginate()->each(function ($val) {
            $val['question'] = json_decode($val['question'], true);

            $username = '';
            if ($user_id = $val['user_id']) $username = Db::name('user')->where(['id' => $user_id])->value('username');
            $val['username'] = $username;

            return $val;
        });
        $this->assign('list', $list);

        $this->assign('title', '做题明细');
        return $this->fetch();
    }

    /**
     * 学习明细
     * */
    public function studentCourseLog()
    {
        $input = Request()->param();

        $id = $input['id'];// 学生id
        $title = $input['title'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (empty($id)) $this->error('学生ID缺失');

        $where['l.user_id'] = $id;

        if ($title) $where['c.title'] = ['like', '%' . $title . '%'];
        if (!empty($start_time) && empty($end_time)) {
            $where["l.study_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["l.study_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["l.study_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('course_log l')
            ->join('study_course c', 'l.course_id = c.id')
            ->field('l.id,c.title,l.study_time,l.category_id,l.user_id')
            ->where($where)->order('c.create_time desc')->paginate()->each(function ($val) {
                $username = '';
                if ($user_id = $val['user_id']) $username = Db::name('user')->where(['id' => $user_id])->value('username');
                $val['username'] = $username;

                return $val;
            });;

        $this->assign('list', $list);
        $this->assign('title', '学习明细');
        return $this->fetch();
    }

    /**
     * 删除学员
     * */
    public function delStudent()
    {
        $id = Request()->param('id');
        if ($id) {
            $info = Db::name('user')->where(['id' => $id])->find();
            if ($info) {
                $res = Db::name('user')->where(['id' => $id])->delete();
                if ($res) {
                    adminReturn(1, '删除成功', url('studentList'));
                } else {
                    adminReturn(2, '删除失败');
                }
            } else {
                adminReturn(2, '学员不存在或已删除');
            }
        } else {
            adminReturn(2, '学员ID缺失');
        }
    }

    /**
     * 老师列表
     * */
    public function teacherList()
    {
        $list = Db::name('user')->where(['user_type' => 1])->paginate();
        $this->assign('list', $list);

        $this->assign('title', '老师列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 老师
     * */
    public function doTeacher()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $username = $input['username'];
            $avatar = $input['avatar'];
            $mobile = $input['mobile'];
            $password = $input['password'];
            $re_password = $input['re_password'];

            if (empty($username)) adminReturn(2, '请输入昵称');
            if (empty($avatar)) adminReturn(2, '请上传头像');
            if (empty($mobile)) adminReturn(2, '请输入手机号');
            if (!preg_match("/^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/", $mobile)) adminReturn(2, '手机号有误，请重新输入');
            if (empty($password)) adminReturn(2, '请输入密码');
            if (strlen($password) < 6) adminReturn(2, '密码长度至少6位');
            if ($password !== $re_password) adminReturn(2, '两次密码不一致，请重新输入');

            $where['mobile'] = $mobile;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('user')->where($where)->count();
            if ($count > 0) adminReturn(2, '该手机号已被使用');

            $time = time();
            $data = [
                'username' => $username,
                'avatar' => $avatar,
                'mobile' => $mobile,
                'account' => $mobile,
                'password' => thinkEncrypt($password),
                'is_admin' => 1,
                'user_type' => 1
            ];

            if ($id) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('user')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('teacherList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('user')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('teacherList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $input = Request()->param();

            $id = $input['id'];

            $info = Db::name('user')->where(['id' => $id])->find();
            $info['password'] = thinkDecrypt($info['password']);
            $this->assign('info', $info);

            $this->assign('title', ($id ? '编辑' : '新增') . '老师');
            return $this->fetch();
        }
    }

    /**
     * 删除老师
     * */
    public function delTeacher()
    {
        $id = Request()->param('id');
        if ($id) {
            $info = Db::name('user')->where(['id' => $id])->find();
            if ($info) {
                $res = Db::name('user')->where(['id' => $id])->delete();
                if ($res) {
                    adminReturn(1, '删除成功', url('teacherList'));
                } else {
                    adminReturn(2, '删除失败');
                }
            } else {
                adminReturn(2, '老师不存在或已删除');
            }
        } else {
            adminReturn(2, '老师ID缺失');
        }
    }

    /**
     * 课程目录
     * */
    public function courseCategoryList()
    {
        $list = Db::name('category')->field('id,name,pid,sort')->where(['type' => 1])->order('sort asc, id asc')->select();
        $this->assign('list_json', json_encode($list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '课程目录');
        return $this->fetch();
    }

    /**
     * 新增/编辑 课程目录
     * */
    public function doCourseCategory()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'] ? : 0;
            $pid = $input['pid'] ? : 0;
            $name = $input['name'];
            $sort = $input['sort'];
            $style = $input['style'] ? : '';

            if (empty($name)) adminReturn(2, '请输入名称');

            $time = time();
            $data = [
                'name' => $name,
                'type' => 1,
                'sort' => $sort
            ];

            if ($style == 'edit') {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('category')->where(['id' => $id])->update($data);
                if ($res) {
                    $top_id = getCourseTopCategoryId($id);
                    $close_top_ids = Db::name('category')->field('id')->where(['pid' => 0, 'id' => ['neq', $top_id]])->select();
                    $close_top_ids = $close_top_ids ? array_column($close_top_ids, 'id') : [];
                    $return_son_ids = [];
                    if ($close_top_ids) {
                        foreach ($close_top_ids as $v) {
                            getCourseSonCategoryIds($v, $son_ids);
                            if ($son_ids) {
                                foreach ($son_ids as $val) {
                                    $return_son_ids[] = $val;
                                }
                            }
                        }
                    }
                    $return_son_ids = array_unique($return_son_ids);

                    $params = ['return_top_ids' => implode(',', $close_top_ids), 'return_son_ids' => implode(',', $return_son_ids)];

                    adminReturn(1, '编辑成功', url('courseCategoryList', $params));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['pid'] = $style == 'add' ? $id : $pid;
                $data['create_time'] = $time;

                $id = Db::name('category')->insertGetId($data);
                if ($id) {
                    if($input['id']){
                        $top_id = getCourseTopCategoryId($id);
                        $close_top_ids = Db::name('category')->field('id')->where(['pid' => 0, 'id' => ['neq', $top_id]])->select();
                        $close_top_ids = $close_top_ids ? array_column($close_top_ids, 'id') : [];
                        $return_son_ids = [];
                        if ($close_top_ids) {
                            foreach ($close_top_ids as $v) {
                                getCourseSonCategoryIds($v, $son_ids);
                                if ($son_ids) {
                                    foreach ($son_ids as $val) {
                                        $return_son_ids[] = $val;
                                    }
                                }
                            }
                        }
                        $return_son_ids = array_unique($return_son_ids);

                        $params = ['return_top_ids' => implode(',', $close_top_ids), 'return_son_ids' => implode(',', $return_son_ids)];

                        adminReturn(1, '新增成功', url('courseCategoryList', $params));
                    }else{
                        adminReturn(1, '新增成功', url('courseCategoryList'));
                    }
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $input = Request()->param();

            $id = $input['id'] ? : '';
            $style = $input['style'] ? : 'add';

            /*if ($id === '') {
                $category_list = Db::name('category')->where(['type' => 1, 'pid' => 0])->order('sort asc, id asc')->select();
                $this->assign('category_list', $category_list);
            }*/

            if ($id && $style === 'edit') {
                $info = Db::name('category')->where(['id' => $id])->find();
                $this->assign('info', $info);
            }

            $this->assign('title', ($style == 'edit' ? '编辑' : '新增') . '课程目录');
            return $this->fetch();
        }
    }

    /**
     * 删除课程目录
     * */
    public function delCourseCategory()
    {
        $id = Request()->param('id');
        if ($id) {
            Db::startTrans();
            try {
                Db::name('category')->where(['id' => $id])->delete();

                getSonCategoryId($id, $son_ids);
                if ($son_ids) Db::name('category')->where(['id' => ['IN', $son_ids]])->delete();

                Db::commit();
                adminReturn(1, '删除成功', url('courseCategoryList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '课程目录ID缺失', url('courseCategoryList'));
        }
    }

    /**
     * 课程列表
     * */
    public function courseList()
    {
        $list = Db::name('course')->order('id desc')->paginate()->each(function ($v) {
            $v['brief'] = $v['brief'] ? subText($v['brief']) : '';
            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '章节列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 课程
     * */
    public function doCourse()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $img = $input['img'];
            $brief = $input['brief'];
            $category_ids = $input['category_ids'];
            $sort = $input['sort'];
            $ppt_id = $input['ppt_id'];
            $ppt_name = $input['ppt_name'];
            $ppt_desc = $input['ppt_desc'];
            $ppt_knowledge = json_decode($input['ppt_knowledge'], true);

            if (empty($title)) adminReturn(-1, '请输入标题');

            $where['title'] = $title;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('course')->where($where)->count();
            if ($count) adminReturn(-1, '标题已存在，请重新输入');

            if (empty($img)) adminReturn(-1, '请上传封面图');
            if (empty($category_ids)) adminReturn(-1, '请选择目录');
            if (empty($ppt_id)) adminReturn(-1, '请上传PPT');
            //            if (empty($ppt_name)) adminReturn(-1, '请输入PPT名称');

            $time = time();
            $data = [
                'title' => $title,
                'img' => $img,
                'brief' => $brief,
                'category_ids' => $category_ids,
                'sort' => $sort,
                'ppt_id' => $ppt_id,
                'ppt_name' => $ppt_name,
                'ppt_desc' => $ppt_desc,
            ];

            Db::startTrans();
            try {
                if ($id) {
                    // 编辑
                    $old_ppt_id = Db::name('course')->where(['id' => $id])->value('ppt_id');
                    if ($old_ppt_id != $ppt_id) {
                        // 修改过PPT
                        $data['ppt_file_index'] = '';
                        $data['ppt_upload_status'] = 0;
                    }

                    $data['update_time'] = $time;

                    Db::name('course')->where(['id' => $id])->update($data);

                    // 录入知识点数据
                    if ($ppt_knowledge) {
                        foreach ($ppt_knowledge as $k => &$v) {
                            $course_knowledge_data = [
                                'name' => $v['knowledge_name'],
                                'course_id' => $id,
                                'ppt_start_page' => $v['ppt_start_page'],
                                'ppt_end_page' => $v['ppt_end_page'],
                                'topic_ids' => $v['topic_ids'] ? implode(',', $v['topic_ids']) : '',
                                'sort' => $k,
                                'update_time' => $time
                            ];
                            if ($v['id'] == 0) {
                                // 新增知识点
                                Db::name('course_knowledge')->insert($course_knowledge_data);
                            } else {
                                // 修改知识点
                                Db::name('course_knowledge')->where(['id' => $v['id']])->update($course_knowledge_data);
                            }
                        }
                    }

                    Db::commit();
                    adminReturn($id, '编辑课程成功', url('courseList'));
                } else {
                    // 新增
                    $data['create_time'] = $time;

                    $id = Db::name('course')->insertGetId($data);

                    $course_knowledge_data = [];
                    foreach ($ppt_knowledge as $k => &$v) {
                        $course_knowledge_data[] = [
                            'name' => $v['knowledge_name'],
                            'course_id' => $id,
                            'ppt_start_page' => $v['ppt_start_page'],
                            'ppt_end_page' => $v['ppt_end_page'],
                            'topic_ids' => $v['topic_ids'] ? implode(',', $v['topic_ids']) : '',
                            'sort' => $k,
                            'update_time' => $time
                        ];
                    }
                    // 新增知识点
                    Db::name('course_knowledge')->insertAll($course_knowledge_data);

                    Db::commit();
                    adminReturn($id, '新增课程成功', url('courseList'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(-1, '提交失败');
            }
        } else {
            $id = Request()->param('id');

            $category_ids = [];
            if ($id) {
                $info = Db::name('course')->where(['id' => $id])->find();
                if ($info) {
                    if ($ppt_id = $info['ppt_id']) $ppt_name = Db::name('file')->where(['id' => $ppt_id])->value('name');
                    $info['ppt_file_name'] = $ppt_name ? : '';

                    $category_ids = explode(',', $info['category_ids']);
                }
                $knowledge_list = Db::name('course_knowledge')->field('id,name knowledge_name,ppt_start_page,ppt_end_page,topic_ids')->where(['course_id' => $id])->order('sort asc')->select();
                if ($knowledge_list) {
                    foreach ($knowledge_list as &$v) {
                        $v['topic_ids'] = $v['topic_ids'] ? explode(',', $v['topic_ids']) : [];
                    }
                }
            } else {
                $knowledge_list = [];
            }

            $this->assign('category_ids', json_encode($category_ids));
            $this->assign('ppt_knowledge', json_encode($knowledge_list));

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '课程');

            $category_list = getCategoryLink(1);
            $this->assign('category_list', json_encode($category_list, JSON_UNESCAPED_UNICODE));

            $topic_list = Db::name('topic')->field('id,question_stem,question,type,tags')->where(['type' => ['IN', '1,2']])->select();
            if ($topic_list) {
                foreach ($topic_list as &$v) {
                    $v['id'] = "'" . $v['id'] . "'";
                    $question = json_decode($v['question'], true);
                    if ($question['img']) $question['img'] = getPicture($question['img']);
                    $v['question'] = $question;
                }
            }
            $this->assign('topic_list', json_encode($topic_list, JSON_UNESCAPED_UNICODE));

            return $this->fetch();
        }
    }

    public function importCourse()
    {
        $input = Request()->param();

        $path = $input['path'];

        if (empty($path)) apiReturn(2, '文件路径为空，请重新上传文件');

        $data = importExcel($path);

        if ($data) {
            $result = [];

            foreach ($data as $k => $v) {
                $title = $v[0];                // 标题
                $img = $v[1];                  // 封面图
                $brief = $v[2];                // 简介
                $category = $v[3];             // 目录
                $ppt_name = $v[4];             // ppt名称
                $ppt_desc = $v[5];             // ppt介绍

                if (empty($title) && empty($img) && empty($brief) && empty($category) && empty($ppt_name) && empty($ppt_desc)) continue;

                $line = $k + 1;

                if (empty($title)) {
                    $error = [
                        'status' => 2,
                        'msg' => '第' . $line . '行数据导入失败；失败原因：标题不能为空'
                    ];
                    $result[] = $error;
                    continue;
                };
                if (empty($img)) {
                    $error = [
                        'status' => 2,
                        'msg' => '第' . $line . '行数据导入失败；失败原因：缺少封面图'
                    ];
                    $result[] = $error;
                    continue;
                }
                if (empty($category)) {
                    $error = [
                        'status' => 2,
                        'msg' => '第' . $line . '行数据导入失败；失败原因：所属目录不能为空'
                    ];
                    $result[] = $error;
                    continue;
                } else {
                    $category_arr = explode('/', $category);
                    if ($category_arr) {
                        $category_res = getCourseCategoryIds($category_arr);
                        if ($category_res && $category_res['result'] != 1) {
                            $error = [
                                'status' => 2,
                                'msg' => '第' . $line . '行数据导入失败；失败原因：' . $category_res['msg']
                            ];
                            $result[] = $error;
                            continue;
                        }
                    } else {
                        $error = [
                            'status' => 2,
                            'msg' => '第' . $line . '行数据导入失败；失败原因：所属目录不能为空'
                        ];
                        $result[] = $error;
                        continue;
                    }
                }

                if (empty($ppt_name)) {
                    $error = [
                        'status' => 2,
                        'msg' => '第' . $line . '行数据导入失败；失败原因：PPT名称不能为空'
                    ];
                    $result[] = $error;
                    continue;
                }

                $title_count = Db::name('course')->where(['title' => $title])->count();
                if ($title_count > 0) {
                    $error = [
                        'status' => 2,
                        'msg' => '第' . $line . '行数据导入失败；失败原因：标题（' . $title . '）已存在'
                    ];
                    $result[] = $error;
                    continue;
                }

                $course_data = [
                    'title' => $title,
                    'img' => $img,
                    'brief' => $brief,
                    'ppt_name' => $ppt_name,
                    'ppt_desc' => $ppt_desc,
                    'create_time' => time(),
                ];

                $res = Db::name('course')->insert($course_data);
                if ($res) {
                    $success = [
                        'status' => 1,
                        'msg' => '第' . $line . '行数据导入成功'
                    ];
                    $result[] = $success;
                } else {
                    $error = [
                        'status' => 2,
                        'msg' => '第' . $line . '行数据导入失败；失败原因：入库失败'
                    ];
                    $result[] = $error;
                }
            }
            apiReturn(1, '导入完成', $result);
        } else {
            apiReturn(2, '文件中未检测到数据');
        }
    }

    /**
     * 删除课程
     * */
    public function delCourse()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '课程ID缺失');

        $info = Db::name('course')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('course')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '课程数据不存在或已删除');
        }
    }

    /**
     * 文献列表
     * */
    public function literatureList()
    {
        $list = Db::name('literature')->order('create_time desc')->paginate()->each(function ($v) {
            $v['course_title'] = Db::name('course')->where(['id' => $v['course_id']])->value('title');
            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '文献列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 文献
     * */
    public function doLiterature()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $course_id = $input['course_id'];
            $title = $input['title'];
            $desc = $input['desc'];
            $ppt_page = $input['ppt_page'];

            if (empty($course_id)) adminReturn(2, '请选择所属课程');
            if (empty($title)) adminReturn(2, '请输入标题');
            if (empty($desc)) adminReturn(2, '请输入说明');
            if (empty($ppt_page)) adminReturn(2, '请输入所在PPT页数');

            $time = time();
            $data = [
                'course_id' => $course_id,
                'title' => $title,
                'desc' => htmlspecialchars($desc),
                'ppt_page' => $ppt_page
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('literature')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('literatureList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('literature')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('literatureList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('literature')->where(['id' => $id])->find();
            }

            $course_list = Db::name('course')->order('sort asc')->select();
            $this->assign('course_list', $course_list);

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文献');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 删除文献
     * */
    public function delLiterature()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文献ID缺失');

        $info = Db::name('literature')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('literature')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 非组合题列表
     * */
    public function topicList()
    {
        $list = Db::name('topic')->where(['type' => 1])->order('create_time desc')->paginate()->each(function ($v) {
            $v['question'] = json_decode($v['question'], true);
            $v['analysis'] = $v['analysis'] ? subText($v['analysis']) : '';
            return $v;
        });

        $this->assign('list', $list);

        $this->assign('title', '非组合题列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 题目
     * */
    public function doTopic()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $question_text = $input['question_text'];
            $question_img = $input['question_img'];
            $option_type = $input['option_type'];
            $option = $input['option'];
            $tags = $input['tags'];
            $analysis = $input['analysis'];

            if (empty($question_text)) apiReturn(2, '请设置提问内容');

            $option_arr = json_decode($option, true);
            if (empty($option_arr)) apiReturn(2, '请设置选项');
            if (count($option_arr) <= 1) apiReturn(2, '请至少设置两个选项');
            $have_true_option = false;
            $have_true_count = 0;
            foreach ($option_arr as &$v) {
                if ($v['answer']) {
                    $have_true_option = true;
                    ++$have_true_count;
                }
            }
            if (!$have_true_option) apiReturn(2, '请选择至少一个正确选项');

            $question = json_encode([
                                        'text' => $question_text,
                                        'img' => $question_img
                                    ], JSON_UNESCAPED_UNICODE);

            $time = time();

            $data = [
                'question' => $question,
                'option_type' => $option_type,
                'option' => $option,
                'tags' => $tags,
                'analysis' => $analysis,
                'style' => $have_true_count > 1 ? 2 : 1
            ];

            if ($id) {
                // 编辑
                $data['update_time'] = $time;

                $res = Db::name('topic')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑题目成功', url('topicList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                // 新增
                $data['create_time'] = $time;

                $res = Db::name('topic')->insert($data);
                if ($res) {
                    adminReturn(1, '新增题目成功', url('topicList'));
                } else {
                    adminReturn(2, '新增题目失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('topic')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '题目');

            return $this->fetch();
        }
    }

    /**
     * 删除题目
     * */
    public function delTopic()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '题目ID缺失');

        $info = Db::name('topic')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('topic')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '题目数据不存在或已删除');
        }
    }

    /**
     * 组合题列表
     * */
    public function groupTopicList()
    {
        $list = Db::name('topic')->where(['type' => 2])->order('create_time desc')->paginate()->each(function ($v) {
            $v['question_stem'] = $v['question_stem'] ? strip_tags(htmlspecialchars_decode($v['question_stem'])) : '';
            $v['topic_count'] = Db::name('topic')->where(['pid' => $v['id']])->count();
            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '组合题列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 组合题
     * */
    public function doGroupTopic()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $question_stem = $input['question_stem'];
            $tags = $input['tags'];

            if (empty($question_stem)) apiReturn(2, '请输入题干');

            $time = time();

            $data = [
                'question_stem' => htmlspecialchars($question_stem),
                'tags' => $tags,
                'type' => 2
            ];

            if ($id) {
                // 编辑
                $data['update_time'] = $time;

                $res = Db::name('topic')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑题目成功', url('groupTopicList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                // 新增
                $data['create_time'] = $time;

                $res = Db::name('topic')->insert($data);
                if ($res) {
                    adminReturn(1, '新增题目成功', url('groupTopicList'));
                } else {
                    adminReturn(2, '新增题目失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('topic')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '组合题');

            return $this->fetch();
        }
    }

    /**
     * 删除组合题
     * */
    public function delGroupTopic()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '组合题ID缺失');

        $info = Db::name('topic')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('topic')->where(['id|pid' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '组合题数据不存在或已删除');
        }
    }

    /**
     * 题目列表
     * */
    public function groupSingleTopicList()
    {
        $id = Request()->param('id');

        $list = Db::name('topic')->where(['pid' => $id])->order('create_time desc')->paginate()->each(function ($v) {
            $v['question'] = json_decode($v['question'], true);
            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '题目列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 题目
     * */
    public function doSingleTopic()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $question_text = $input['question_text'];
            $question_img = $input['question_img'];
            $option_type = $input['option_type'];
            $option = $input['option'];
            $analysis = $input['analysis'];
            $pid = $input['pid'];

            if (empty($question_text) && empty($question_img)) apiReturn(2, '请设置提问内容');

            $option_arr = json_decode($option, true);
            if (empty($option_arr)) apiReturn(2, '请设置选项');
            if (count($option_arr) <= 1) apiReturn(2, '请至少设置两个选项');
            $have_true_option = false;
            $have_true_count = 0;
            foreach ($option_arr as &$v) {
                if ($v['answer']) {
                    $have_true_option = true;
                    ++$have_true_count;
                }
            }
            if (!$have_true_option) apiReturn(2, '请选择至少一个正确选项');

            $question = json_encode([
                                        'text' => $question_text,
                                        'img' => $question_img
                                    ], JSON_UNESCAPED_UNICODE);

            $time = time();

            $data = [
                'question' => $question,
                'option_type' => $option_type,
                'option' => $option,
                'analysis' => $analysis,
                'style' => $have_true_count > 1 ? 2 : 1,
                'type' => 3,
                'pid' => $pid
            ];

            if ($id) {
                // 编辑
                $data['update_time'] = $time;

                $res = Db::name('topic')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑题目成功', url('groupSingleTopicList', ['id' => $pid]));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                // 新增
                $data['create_time'] = $time;

                $res = Db::name('topic')->insert($data);
                if ($res) {
                    adminReturn(1, '新增题目成功', url('groupSingleTopicList', ['id' => $pid]));
                } else {
                    adminReturn(2, '新增题目失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('topic')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '题目');

            return $this->fetch();
        }
    }

    /**
     * 删除题目
     * */
    public function delSingleTopic()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '题目ID缺失');

        $info = Db::name('topic')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('topic')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '题目数据不存在或已删除');
        }
    }

    /**
     * 会员统计
     * */
    public function userCensus()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($start_time) && empty($end_time)) {
            $where["create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('user')->where(['user_type' => 2])->where($where)->paginate()->each(function ($v) {
            $teacher_username = '';
            if ($up_user_id = $v['up_user_id']) $teacher_username = Db::name('user')->where(['id' => $up_user_id])->value('username');
            $v['teacher_username'] = $teacher_username;

            return $v;
        });
        $this->assign('list', $list);

        $time_list = Db::name('user')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->where(['user_type' => 2])->where($where)->order('create_time asc')->select();
        $student_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $student_count = Db::name('user')->where(['user_type' => 2, 'create_time' => ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]]])->count();
                $student_list[] = $student_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('student_list', json_encode($student_list));

        $this->assign('title', '会员统计');
        return $this->fetch();
    }

    /**
     * 错题占比
     * */
    public function errorTopicCensus()
    {
        $input = Request()->param();

        $course_id = $input['course_id'];

        if ($course_id) $where['c.course_id'] = $course_id;

        $list = Db::name('topic_census c')->join('study_topic t', 'c.topic_id = t.id')
            ->field('c.id,c.course_id,c.topic_id,t.question_stem,t.question,t.pid,c.do_count,c.error_count,c.error_rate,t.type')
            ->where($where)
            ->paginate()->each(function ($v) {
                if ($v['pid']) $question_stem = Db::name('topic')->where(['id' => $v['pid']])->value('question_stem');
                $v['question_stem'] = $question_stem ? subText($question_stem) : '';

                $v['question'] = json_decode($v['question'], true);

                $course_title = Db::name('course')->where(['id' => $v['course_id']])->value('title');
                $v['course_title'] = $course_title ? : '';
                return $v;
            });
        $this->assign('list', $list);

        $course_list = Db::name('course')->order('sort asc')->select();
        $this->assign('course_list', $course_list);

        $this->assign('title', '错题占比');
        return $this->fetch();
    }

    /**
     * 目录学习占比
     * */
    public function categoryCensus()
    {
        $input = Request()->param();

        $course_id = $input['course_id'];

        if ($course_id) $where['l.course_id'] = $course_id;

        $count = Db::name('course_log')->sum('count');

        $list = Db::name('course_log l')->join('study_course c', 'l.course_id = c.id', 'left')
            ->field('sum(count) count,l.category_id,c.title')
            ->group('category_id')
            ->where($where)
            ->paginate()->each(function ($val) use ($count) {
                $category_name = Db::name('category')->where(['id' => $val['category_id']])->value('name');
                $val['category_name'] = $category_name ? : '';

                $val['rate'] = sprintf('%.2f', $val['count'] / $count * 100);

                $course_title = Db::name('course')->where(['id' => $val['course_id']])->value('title');
                $val['course_title'] = $course_title ? : '';

                return $val;
            });

        $this->assign('list', $list);

        $course_list = Db::name('course')->order('sort asc')->select();
        $this->assign('course_list', $course_list);

        $this->assign('title', '目录学习占比');
        return $this->fetch();
    }

    /**
     * 微信讨论群列表
     * */
    public function weChatList()
    {
        $list = Db::name('we_chat')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '微信讨论群列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 微信讨论群
     * */
    public function doWeChat()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $img = $input['img'];

            if (empty($img)) adminReturn(2, '请上传图片');
            if (empty($name)) adminReturn(2, '请输入微信群名称');

            $time = time();
            $data = [
                'img' => $img,
                'name' => $name
            ];

            if ($id) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('we_chat')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('weChatList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('we_chat')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('weChatList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $input = Request()->param();

            $id = $input['id'];

            $info = Db::name('we_chat')->where(['id' => $id])->find();
            $this->assign('info', $info);

            $this->assign('title', ($id ? '编辑' : '新增') . '微信讨论群');
            return $this->fetch();
        }
    }

    /**
     * 删除微信讨论群
     * */
    public function delWeChat()
    {
        $id = Request()->param('id');
        if ($id) {
            $info = Db::name('we_chat')->where(['id' => $id])->find();
            if ($info) {
                $res = Db::name('we_chat')->where(['id' => $id])->delete();
                if ($res) {
                    adminReturn(1, '删除成功', url('weChatList'));
                } else {
                    adminReturn(2, '删除失败');
                }
            } else {
                adminReturn(2, '微信讨论群不存在或已删除');
            }
        } else {
            adminReturn(2, '微信讨论群ID缺失');
        }
    }


}
